package controllers;

import play.*;
import play.db.jpa.GenericModel.JPAQuery;
import play.mvc.*;

import java.util.*;

import org.apache.commons.mail.EmailException;

import models.*;

@With(Secure.class)
// this class is used for the login, Doaa El-Hawary
public class Requests extends Controller {

	public static void index() {
		render();
	}

	/**
	 * Changes the value of boolean saveAsDraft to true.
	 * 
	 * @author karim khalaf
	 * @version 2010.0502
	 * @category C3S9
	 * @parameter sender
	 * @param receiver
	 * @param topicDescription
	 * @param date
	 *            : the date where the request has been created.
	 * @param saveAsDraft
	 *            : boolean to indicate if the request is draft or not.
	 * @param type
	 *            : a string indicating the type of the request.
	 * @return Boolean: true if request is saved as draft.
	 */

	
	
	public static void saveDraft(long receiverId,
			String TopicDescription, boolean saveAsDraft) {
		String name = session.get("username");
		User sender = (User) User.find("byUsername", name).fetch().get(0);
		User receiver = (User) User.find("byId", receiverId).fetch().get(0);
		Request request = new Request(sender, receiver, TopicDescription,
				saveAsDraft, "Topic Request");
		request.save();
		List<Request> a = Request.findAll();
		System.out.println(a.get(0).getContent());
		render();
		

	}

	/**
	 * User send a justified request to the organizer, this is what's sent to
	 * the html file
	 * 
	 * @author Omar Hassab
	 * @version 2011.0506
	 * @category C5S10
	 * @param nothing
	 * @return nothing
	 */
	public static void justifiedRequestView() {
		User user = (User.find("byUsername", Security.connected()).first());
		System.out.println(user.getlName());
		long userID =user.getId(); 
		List<Item> allItems = Item.findAll();
		render(userID, allItems);
	}
	
	/**
	 * creates justified request to volunteer in an item in an action plan
	 * 
	 * @author Caroline Tawfik
	 * @version 2010.0502
	 * @category C3D4
	 * @parameter long itemID: the ID the user wishes to volunteer in String
	 *            justification: explanation why he wants to volunteer item: the
	 *            item he wishes to volunteer in
	 * @return nothing
	 * @throws EmailException
	 */
	public static void justifiedRequest(String justification, long itemId)
			throws EmailException {
		String name = session.get("username");
		User sender = (User) User.find("byUsername", name).fetch().get(0);
		Item item = Item.findById(itemId);
		Plan plan = item.getPlan();

		// Omar Hassab to Caroline
		// these two condition check if the user is already assigned to the item
		// or if the item is completed, in that case he can no longer volunteer;
		// and each will render a different message
		if (item.getUsers().contains(sender)) {
			String x = "You are already assigned to the plan";
			render(x);
		}

		if (item.isCompleted()) {
			String x = "Item is completed, you can't be assigned to it";
			render(x);
		}

		// Omar Hassab to Caroline
		// this loop checks if the sender is an organizer, and if so, it renders
		// x and doesn't send a request, since by default organizers are
		// assigned to work on action items
		for (int i = 0; i < sender.getRoleList().size(); i++) {
			if (sender.getRoleList().get(i).getTitle()
					.equalsIgnoreCase("organizer")) {
				String x = "organizer can't send a volunteer request, he can immediately work on the plan";
				render(x);
			}
		}
		LinkedList<User> list = new LinkedList<User>();
		for (int i = 0; i < plan.getUsers().size(); i++) {
			for (int j = 0; j < plan.getUsers().get(i).getRoleList().size(); j++) {
				if (plan.getUsers().get(i).getRoleList().get(j).getTitle()
						.equalsIgnoreCase("Organizer")) {
					list.add(plan.getUsers().get(i));
				}
			}
		}
		
		for (int j = 0; j < list.size(); j++) {
			String subject = sender.getfName()
					+ " "
					+ sender.getlName()
					+ "has requested to volunteer in an item in a certain action plan.";
			String content = sender.getfName() + " " + sender.getlName()
					+ "has requested to volunteer in the item:\n "
					+ item.getContent() + "\n in the action plan: \n"
					+ plan.getName() + "\n for the following reason:\n "
					+ justification;
			sender.sendNotification(list.get(j), subject, content);

			Request request = new Request(sender, list.get(j), content, false,
					"action plan request");
			request.save();
		}

		// Omar Hassab to Caroline
		// these lines will render the success message to the other view
		// indicating that the request is successfully sent
		String x = "request sent successfully";
		render(x);
	}

	/**
	 * Adds a rating to a request then showing the view with the new overall
	 * rating calculated
	 * 
	 * @author Arwa Ismail
	 * @version 2011.0429
	 * @category C4S10
	 * @params rater: The user that performed the rating, rate: the rate chosen
	 *         for the request requestID: The id of the request
	 */

	/*
	 * public static void addRating (User rater, String rate, int requestID) {
	 * Request request = new Request().findById(requestID); Rating r = new
	 * Rating (rater, rate); request.getRatings().add(r); int newRating =
	 * request.calculateAverageRating(); render(newRating,requestID); // show a
	 * confirmation message that the rating is added // show the new average
	 * rating
	 * 
	 * }
	 */

	/**
	 * view the requests of merged ideas
	 * 
	 * @author Aly Mostafa
	 * @version 2011.0429
	 * @category C3S17
	 * @params Long id the request id
	 */

	public static void viewMergeRequest(long id) {

		String name = Security.connected();
		User user = (User) User.findByUsername(name);
		
		
		
		Request request = Request.findById(id);
		String s = request.getContent();
		String[] array = s.split("-", 4);
		long idea1 = Long.parseLong(array[0]);
		long idea2 = Long.parseLong(array[1]);
		long belonger = Long.parseLong(array[2]);
		String var = array[3];
		
		Idea x = Idea.findById(idea1);
		Idea y = Idea.findById(idea2);

		String idea1details = x.getIdeaDetail();
		String idea2details = y.getIdeaDetail();
		
		if(var.equals("topic")){
			if(x.getTopic().getInitiator().equals(user)|| x.getOrganization().getLead()==user)
				render(idea1, idea2, request, belonger, var, idea1details, idea2details);
			else
				error("you are not authorized");
		}else{
			if(var.equals("entity")){
				if(x.getEntity().getOrganizers().contains(user)|| x.getOrganization().getLead()==user)
					render(idea1, idea2, request, belonger, var, idea1details, idea2details);
				else
					error("you are not authorized");
			}else{
				if(x.getOrganization().getOrganizers().contains(user)|| x.getOrganization().getLead()==user)
					render(idea1, idea2, request, belonger, var, idea1details, idea2details);
				else
					error("you are not authorized");
			}
		}
		
		

	}
	/**
	 * helper method to render parameters
	 * 
	 * @author Aly Mostafa
	 * @version 2011.05.06
	 * @category C3S17
	 * @params takes the 2 idaes the thing it belongs to and the 2 idea details
	 */
	public static void helper(long idea1, long idea2,long belonger, String var,String idea1details,String idea2details) {

		render(idea1, idea2, belonger, var,idea1details, idea2details);

	}
	
	public static void viewRequestByType(String Type){
	List<Request> requests = Request.find("byType", Type).fetch();
	render(requests);
	}
	
	public static void viewAllRequests(){
		List<Request> requests = Request.findAll();
		render(requests);
	}
	
	public static void viewRequest(long requestid){
		Request req= Request.findById(requestid);
		
		String x = "";
		if(req == null){
			x = "request is not found";
			error(x);

		}
		else if (req.getType().equalsIgnoreCase("merge")) {
			
			viewMergeRequest(req.id);
		}else
		{render(req);}

		
	}
	
}


